package com.ding.eduservice.entity.excel;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.util.ConverterUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ding.eduservice.entity.EduSubject;
import com.ding.eduservice.service.EduSubjectService;
import com.ding.servicebase.exceptionmanage.Dingexception;

import javax.management.Query;
import java.util.Map;

public class SubjectListener extends AnalysisEventListener<Excel>{

    //因为SubjectListener不能交给spring管理，需要自己new，不能注入其他对象
    //不能实现数据库操作

    public EduSubjectService subjectService;

    public SubjectListener() {}

    public SubjectListener(EduSubjectService subjectService) {
        this.subjectService = subjectService;
    }


    @Override
    public void invokeHead(Map<Integer, CellData> headMap, AnalysisContext context) {

    }
    //读取excel内容，一行进行读取
    @Override
    public void invoke(Excel excel, AnalysisContext analysisContext) {
      if(excel == null){
          throw new Dingexception(20001,"文件数据为空");
      }
      //一行的读取，每次读取有两个值
      //判断一级分类是否重复
        EduSubject eduoneSubject = this.existOneSubject(subjectService, excel.getOneSubject());
      if(eduoneSubject == null){//没有相同的一级分类
          eduoneSubject = new EduSubject();
          eduoneSubject.setParentId("0");
          eduoneSubject.setTitle(excel.getOneSubject());
         subjectService.save(eduoneSubject);
      }

      //获取一级分类的id值
       String pid = eduoneSubject.getId();

      //添加二级分类
      //判断二级分类是否重复
        EduSubject eduTwoSubject = this.existTwoSubject(subjectService, excel.getTwoSubject(), pid);
         if(eduTwoSubject == null){
             eduTwoSubject = new EduSubject();
             eduTwoSubject.setParentId(pid);
             eduTwoSubject.setTitle(excel.getTwoSubject());//二级分类
             subjectService.save(eduTwoSubject);
         }

    }

    //判断一级分类不能重复添加
    private EduSubject existOneSubject(EduSubjectService eduSubjectService,String name){
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("title",name);
        wrapper.eq("parent_id","0");
        EduSubject one = subjectService.getOne(wrapper);
        return one;
    }

    //判断二级分类不能重复添加
    private EduSubject existTwoSubject(EduSubjectService eduSubjectService,String name,String pid){
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("title",name);
        wrapper.eq("parent_id",pid);
        EduSubject two = subjectService.getOne(wrapper);
        return two;
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
